// ==========================================================================
// GEA自动生成业务逻辑层相关代码，只生成一次，按需修改,再次生成不会覆盖.
// 生成日期：{{.table.CreateTime}}
// 生成路径: app/system/{{.table.ModuleName}}/internal/service/{{.table.BusinessName | CamelLower}}.go
// 生成人：{{.table.FunctionAuthor}}
// ==========================================================================
package service

import (
    "context"
    "fmt"
    "gea/app/dao"
    "gea/app/model"
    "gea/app/shared"
    "gea/app/system/{{.table.ModuleName}}/internal/define"
    "gea/app/utils/convert"
    "gea/app/utils/excel"
    "gea/app/utils/page"
    "github.com/gogf/gf/errors/gerror"
    "github.com/gogf/gf/os/gtime"
    "github.com/gogf/gf/util/gconv"
)

var {{.table.BusinessName | CamelString}} = new({{.table.BusinessName | CamelLower}}Service)

type {{.table.BusinessName| CamelLower}}Service struct {}

// Info 根据主键查询数据
func (s *{{.table.BusinessName | CamelLower}}Service) Info(id int64) (*model.{{.table.TableName | CamelString}}, error) {
    return dao.{{.table.TableName | CamelString}}.FindOne(dao.{{.table.TableName | CamelString}}.Columns.{{.table.PkColumn.GoField}},id)
}


// GetList 根据条件分页查询数据
func (s *{{.table.BusinessName | CamelLower}}Service)GetList(param *define.{{.table.BusinessName | CamelString}}ApiSelectPageReq) {{if ne .table.TplCategory "tree"}}*define.{{.table.BusinessName | CamelString}}ServiceList{{else}}[]*model.{{.table.TableName | CamelString}}{{end}} {
    m := dao.{{.table.TableName | CamelString}}.As("t")
    if param != nil { {{range $index, $column := .table.Columns}} {{if eq $column.IsQuery "1"}}{{if eq $column.QueryType "LIKE"}}
        if param.{{$column.GoField}} != "" {
            m = m.Where("t.{{$column.ColumnName}} like ?", "%"+param.{{$column.GoField}}+"%")
        } {{else if eq $column.QueryType "EQ"}} {{if eq $column.GoType "string"}}
        if param.{{$column.GoField}} != "" {
            m = m.Where("t.{{$column.ColumnName}} = ?", param.{{$column.GoField}})
        } {{else if eq $column.GoType "int" "int64"}}
        if param.{{$column.GoField}} != 0 {
            m = m.Where("t.{{$column.ColumnName}} = ?", param.{{$column.GoField}})
        }{{end}} {{end}} {{end}} {{end}}
        if param.BeginTime != "" {
            m = m.Where("date_format(t.create_time,'%y%m%d') >= date_format(?,'%y%m%d') ", param.BeginTime)
        }
        if param.EndTime != "" {
            m = m.Where("date_format(t.create_time,'%y%m%d') <= date_format(?,'%y%m%d') ", param.EndTime)
        }
    }
    {{if ne .table.TplCategory "tree"}}
    total, err := m.Count()
    if err != nil {
        return nil
    }
    page := page.CreatePaging(param.PageNum, param.PageSize, total)
    m = m.Limit(page.StartNum, page.Pagesize)
    if param.OrderByColumn != "" {
        m = m.Order(param.OrderByColumn + " " + param.IsAsc)
    }
    result := &define.{{.table.BusinessName | CamelString}}ServiceList{
        Page:  page.PageNum,
        Size:  page.Pagesize,
        Total: page.Total,
    }
    if err = m.Structs(&result.List); err != nil {
        return nil
    }
    {{else}}
    result := []*model.{{.table.TableName | CamelString}}
    if err := m.Structs(&result); err != nil {
        return nil
    }
    {{end}}
    return result
}

// Create 添加数据
func (s *{{.table.BusinessName | CamelLower}}Service) Create(ctx context.Context, req *define.{{.table.BusinessName | CamelString}}ApiCreateReq) (int64, error) {
    user := shared.Context.Get(ctx).User
    var entity model.{{.table.TableName | CamelString}}
    // 写你自己的字段，例如CreateTime，CreateBy
    var editReq *define.{{.table.BusinessName | CamelString}}ApiUpdateReq
    gconv.Struct(req, &editReq)
    return s.save(&entity, editReq)
}

// Update 修改数据
func (s *{{.table.BusinessName | CamelLower}}Service) Update(ctx context.Context, req *define.{{.table.BusinessName | CamelString}}ApiUpdateReq) (int64, error) {
    user := shared.Context.Get(ctx).User
    entity, err := dao.{{.table.TableName | CamelString}}.FindOne(dao.{{.table.TableName | CamelString}}.Columns.{{.table.PkColumn.GoField}}, req.{{.table.PkColumn.GoField}})
    if err != nil {
        return 0, err
    }
    if entity == nil {
        return 0, gerror.New("数据不存在")
    }
    // 写你自己的字段，例如UpdateTime，UpdateBy
    return s.save(entity, req)
}

func (s *{{.table.BusinessName | CamelLower}}Service) save({{.table.BusinessName | CamelLower}} *model.{{.table.TableName | CamelString}}, req *define.{{.table.BusinessName | CamelString}}ApiUpdateReq) (int64, error) {
    var (
        rs  int64
        err error
    )
    {{range $index, $column := .table.Columns}}
    {{if and (eq $column.IsInsert "1") (ne $column.IsPk "1")}}{{$.table.BusinessName | CamelLower}}.{{$column.GoField}} = req.{{$column.GoField}} {{end}}{{end}}
    result, err := dao.{{.table.TableName | CamelString}}.Data({{.table.BusinessName | CamelLower}}).Save()
    if err != nil {
        return 0, err
    }
    if {{.table.BusinessName | CamelLower}}.{{.table.PkColumn.GoField}} == 0 {
        // 新增
        rs, err = result.LastInsertId()
    } else {
        rs, err = result.RowsAffected()
    }
    if err != nil {
        return 0, err
    }
    return rs, nil
}

// Delete 批量删除数据记录
func (s *{{.table.BusinessName | CamelLower}}Service) Delete(ids string) int64 {
    idarr := convert.ToInt64Array(ids, ",")
    field := fmt.Sprintf("%s in(?)", dao.{{.table.TableName | CamelString}}.Columns.{{.table.PkColumn.GoField}})
    result, err := dao.{{.table.TableName | CamelString}}.Delete(field, idarr)
    if err != nil {
        return 0
    }
    nums, _ := result.RowsAffected()
    return nums
}

// Export 导出excel
func (s *{{.table.BusinessName | CamelLower}}Service) Export(param *define.{{.table.BusinessName | CamelString}}ApiSelectPageReq) (string, error) {
    m := dao.{{.table.TableName | CamelString}}.As("t")
    if param != nil { {{range $index, $column := .table.Columns}} {{if eq $column.IsQuery "1"}}{{if eq $column.QueryType "LIKE"}}
        if param.{{$column.GoField}} != "" {
            m = m.Where("t.{{$column.ColumnName}} like ?", "%"+param.{{$column.GoField}}+"%")
        } {{else if eq $column.QueryType "EQ"}} {{if eq $column.GoType "string"}}
        if param.{{$column.GoField}} != "" {
            m = m.Where("t.{{$column.ColumnName}} = ?", param.{{$column.GoField}})
        } {{else if eq $column.GoType "int" "int64"}}
        if param.{{$column.GoField}} != 0 {
            m = m.Where("t.{{$column.ColumnName}} = ?", param.{{$column.GoField}})
        }{{end}} {{end}} {{end}} {{end}}
        if param.BeginTime != "" {
            m = m.Where("date_format(t.create_time,'%y%m%d') >= date_format(?,'%y%m%d') ", param.BeginTime)
        }
        if param.EndTime != "" {
            m = m.Where("date_format(t.create_time,'%y%m%d') <= date_format(?,'%y%m%d') ", param.EndTime)
        }
    }
    //"参数主键","参数名称","参数键名","参数键值","系统内置（Y是 N否）","状态"
    m = m.Fields("{{range $index, $column := .table.Columns}} {{if eq $index 0}}t.{{$column.ColumnName}}{{else}},t.{{$column.ColumnName}}{{end}}{{end}}")
    result, err := m.M.All()
    if err != nil {
        return "", err
    }
    head := []string{ {{range $index, $column := .table.Columns}} {{if eq $index 0}}"{{$column.ColumnComment}}"{{else}},"{{$column.ColumnComment}}"{{end}}{{end}}}
    key := []string{ {{range $index, $column := .table.Columns}} {{if eq $index 0}}"{{$column.ColumnName}}"{{else}},"{{$column.ColumnName}}"{{end}}{{end}}}
    filename := "{{.table.FunctionName}}导出_"+gtime.Date() + ".xlsx"
    url, err := excel.DownlaodExcel(head, key, result,filename)
    if err != nil {
        return "", err
    }
    return url, nil
}